<?php
/**
 * @author wyl
 * @date 2015-8-27 13:53:43
 */
Yii::import('dao.auction.AuctionDetailDao');
Yii::import('system.web.widgets.CWidget');
class BuyitnowButton extends CWidget{
	public $label;
	public $url;
	public $auction_id;
	public $ajaxUrl;
	public $loginUrl;
	
	public function init(){
		$this->label=(empty($this->label))?'Buy it now':$this->label;
		$this->url=Yii::app()->baseUrl.'/checkout/index?id='.$this->auction_id.'&orderType=2';
		$this->ajaxUrl=Yii::app()->baseUrl.'/ajax/ajaxbuyitnow';
		$this->loginUrl=Yii::app()->baseUrl.'/login?url='.strrchr(Yii::app()->request->getUrl(),"a");
	}
	
	public function run(){
		$this->renderBidButton();
		$this->addScript();	
	}
	 
	public function renderBidButton(){
		echo CHtml::htmlButton($this->label,
			array(
				'class'			=>'btn btn-default buy-it-now-now auction-buy-it-now',
				'aid'			=>$this->auction_id,
		));
	}
	
	/**
	 * 获取价格
	 */
	public function getBINPrice(){
	    $auction=new AuctionDetailDao();
	    $auction->find($this->auction_id);
	    return !empty($auction->value_price)?$auction->value_price:0;
	}
	
	public function addScript(){
		Yii::app()->clientScript->registerScript('buy-it-now-button-js',"
				$('.buy-it-now-now').on('click',function(){
					var ajaxbin={'auction_id':{$this->auction_id}};
					var binPrice={$this->getBINPrice()};
					$.ajax({
							url:'{$this->ajaxUrl}',
							data:ajaxbin,
							type:'post',
							dataType:'json',
							success:function(data){
								if(data.hasOwnProperty('nologin')){
									window.location.href='{$this->loginUrl}';
								}else if(data.hasOwnProperty('error')){
									alert(data.error);
								}
								else{
                					ga('send', 'event', { eventCategory: 'bin', eventAction: 'purchase', eventValue: binPrice});
									window.location.href='{$this->url}';
								}
							}
					})
				})
		");
		Yii::app()->clientScript->registerCss('buy-it-now-button-css', "
			.btn.buy-it-now-now{
		        width:142px;
				padding:auto 35px;

				font-size:15px;
				border:none;
		        color:#ffffff;
				background-color:#0FBAE8;
		        
			}
		");
	}
}		
